

package com.ikas.autumn.iec104.common.util.date;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateUtils {
    private DateUtils() {
    }
    private static final String[] FMT = {"y", "M", "d", "H", "m", "s", "S"};

    public static String inferDateFormat(String src) {
        int fmtIdx = 0;
        boolean findMatch = false;
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < src.length(); i++) {
            char chr = src.charAt(i);
            if (Character.isDigit(chr)) {
                findMatch = true;
                stringBuilder.append(FMT[fmtIdx]);
            } else {
                if (findMatch) {
                    fmtIdx++;
                    findMatch = false;
                }
                stringBuilder.append(chr);
            }
            if (fmtIdx == FMT.length - 1 && i < src.length() - 1) {
                stringBuilder.append(src.substring(i + 1));
                break;
            }
        }
        return stringBuilder.toString();
    }

    public static boolean isDateFormat(String format) {
        return StringUtils.isNotBlank(format) && "yyyy-MM-dd".equalsIgnoreCase(format.trim());
    }

    public static boolean isDateTimeFormat(String format) {
        return StringUtils.isNotBlank(format) && "yyyy-MM-dd HH:mm:ss".equalsIgnoreCase(format.trim());
    }

    public static String withTimeString(String name) {
        return name + DateFormatUtils.format(new Date(), DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss.SSS"));
    }

    /**
     * 日期向后或者向前推移
     * @param intervalDay 日期推移值；如：1，传入日期参数向后推一天；-1，传入日期参数向前推一天
     * @return 返回推移后的日期字符串
     */
    public static Date dayAddOrCut(Date date, int intervalDay){
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, intervalDay);
        return calendar.getTime();
    }
}
